package com.htbb.common.mq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class MqReceiver implements MessageListener {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	// ConnectionFactory ：连接工厂，JMS 用它创建连接
	public ConnectionFactory connectionFactory = null;
	// Connection ：JMS 客户端到JMS Provider 的连接  
	public Connection connection = null;
	// Session： 一个发送或接收消息的线程  
	public Session session = null;
	// 消费者，消息接收者  
	public MessageConsumer consumer = null;
	// Destination ：消息的目的地;消息发送给谁
	public Destination destination = null;

	public MqReceiver(){
	}

	/**
	 * 启动
	 */
	public void start(){
		init();
	}

	/**
	 * 初始化
	 */
	public void init(){

		try{
			connectionFactory = new ActiveMQConnectionFactory(
					ActiveMQConnection.DEFAULT_USER,
					ActiveMQConnection.DEFAULT_PASSWORD,Config.MQ_SERVER);

			// 构造从工厂得到连接对象  
			connection = connectionFactory.createConnection();
			//启动
			connection.start();
			// 获取操作连接
			session = connection.createSession(Boolean.FALSE,  
					Session.AUTO_ACKNOWLEDGE);  
			// 获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置  
			destination = session.createQueue(Config.QUEUE_NAME);  
			consumer = session.createConsumer(destination);  

			// 开始监听
			consumer.setMessageListener(this);

		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {  
				//if (null != connection)  
				//connection.close();  
			} catch (Throwable ignore) {  
			} 
		}
	}

	/**
	 * 接收消息
	 */
	@Override
	public void onMessage(Message message) {
		try {
			if (message instanceof MapMessage) {

				MapMessage msgMap = (MapMessage) message;
				int type = msgMap.getInt("type");
				String msg = msgMap.getString("jsonMsg");
				MqClientUtil.getInstance().messageReceived(type,msg.toString());
			} else {
				logger.info("接收到非约定类型mq消息: " + message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 关闭连接
	public void close(){
		try {
			if (consumer != null)
				consumer.close();
			if (session != null)
				session.close();
			if (connection != null)
				connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}


}
